package com.datounet.flutterapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;

public class WakeUpHelper {
    static private PowerManager.WakeLock wakeLock;

    @SuppressLint("InvalidWakeLockTag")
    public static void init(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象
        wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
    }

    public static void wakeLockRelease() {
        if (wakeLock == null) {
            return;
        }
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
    }

    public static void wakeLockGet() {
        if (wakeLock == null) {
            return;
        }
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
        wakeLock.acquire();
    }

    public static void popForeground(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClass(context, MainActivity.class);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        context.startActivity(intent);
    }

    public static void openLock(Context context) {
        KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            keyguardManager.requestDismissKeyguard(MainActivity.instance, new KeyguardManager.KeyguardDismissCallback() {
                @Override
                public void onDismissError() {
                    Log.e("keyguardManager", "onDismissError: ");
                    super.onDismissError();
                }

                @Override
                public void onDismissSucceeded() {
                    Log.e("keyguardManager", "onDismissSucceeded: ");

                    super.onDismissSucceeded();
                }

                @Override
                public void onDismissCancelled() {
                    Log.e("keyguardManager", "onDismissCancelled: ");
                    super.onDismissCancelled();
                }
            });
        }else {
            KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
            keyguardLock.disableKeyguard();
        }

    }

}
